// pages/bill/modify.js
const app = getApp()
import { billEdit, billSave, feeQuery } from '../../utils/conf';
import Toast from 'tdesign-miniprogram/toast/index';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    overlay: false,
    list: {
      'bill_type_note': '',
    },
    // 年月日选择框
    pickerText: '月',
    pickerValue: ['month'],
    pickerArr: [
      { label: '年', value: 'year' },
      { label: '月', value: 'month' },
      { label: '日', value: 'day' },
    ],
    pickerVisible: false,
    feeArr: [],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getFeeData();
    this.getData(options.id);
  },

  async getFeeData() {
    try {
      const res = await app.call({
        path: feeQuery,
        method: 'GET'
      });
      this.setData({
        feeArr: res.data,
      });
    } catch (error) {
      // 添加错误处理逻辑，可以在这里弹出提示或者记录错误
      console.error('获取其他收费项目失败:', error);
    }
  },

  async getData(id) {
    try {
      const res = await app.call({
        path: billEdit,
        method: 'POST',
        data: { id }
      });
      this.setData({
        list: res.data,
      });
    } catch (error) {
      console.error('获取数据失败:', error);
      this.showToast('获取数据失败', 'error');
    }
  },

  bindDataChange(e) {
    const { key } = e.currentTarget.dataset;
    const { value } = e.detail;
    // 直接对this.data.list进行修改，并调用this.setData
    this.setData({
      ['list.' + key]: value
    });
  },

  verification() {
    const { list } = this.data;
    const baseRequiredFields = {
      rental: '租金不能为空',
      deposit: '押金不能为空',
      daily_rent: '逾期日租金',
      water_price: '水费单价',
      electricity_price: '电费单价',
      ratio: '水电倍率',
    };

    const requiredFields = {
      ...baseRequiredFields,
      ...this.data.feeArr.reduce((acc, element) => {
        if (element?.column_name && element?.column_id) {
          acc[element.column_id] = element.column_name;
        }
        return acc;
      }, {})
    };

    for (const key in requiredFields) {
      if (list[key] === '' || list[key] === undefined || list[key] === null) {
        return { res: false, msg: requiredFields[key] };
      }
    }

    return { res: true, msg: '' };
  },

  async bindSave() {
    let res = this.verification();
    if (!res.res) {
      this.showToast(res.msg);
      return;
    }
    this.setData({ overlay: true });
    let list = { ...this.data.list };

    try {
      const saveResult = await app.call({
        path: billSave,
        method: 'POST',
        data: list
      });
      this.setData({ overlay: false });
      let icon = saveResult.code === 1 ? 'success' : 'warning';
      this.showToast(saveResult.msg, icon);
      if (saveResult.code !== 0) {
        setTimeout(() => {
          wx.navigateBack({ delta: 1 });
        }, 1000);
      }
    } catch (err) {
      this.setData({ overlay: false });
      // 增加错误处理逻辑，比如显示Toast提示用户
      console.error('保存失败:', err);
      this.showToast('保存失败，请稍后再试', 'error');
    }
  },

  onPickerChange(e) {
    let newData = { ...this.data.list };
    newData['cycle_type'] = e.detail.value[0];
    this.setData({
      pickerText: e.detail.label[0],
      pickerValue: [e.detail.value[0]],
      pickerVisible: false,
      list: newData
    });
  },
  onSelect() {
    this.setData({
      pickerVisible: true,
      pickerValue: [this.data.list.cycle_type]
    });
  },

  /**
   * 显示Toast提示框
   *
   * @param message 提示框显示的内容
   * @param theme 提示框的主题，默认为'none'
   */
  // 
  showToast(message, theme = 'none') {
    Toast({
      context: this,
      selector: '#t-toast',
      message: message,
      theme: theme
    });
  },
})